<script setup lang="ts">
import { onMounted, ref } from "vue";
import { message } from "@/utils/message";
import { deviceDetection } from "@pureadmin/utils";
import { getUserProfile,editUserProfile,deleteUserProfile } from "@/swagger/api/user";
import { de } from "element-plus/es/locale/index.mjs";

defineOptions({
  name: "Preferences"
});

const list = ref([
  {
    key: "账户密码",
    description: "其他用户的消息将以站内信的形式通知",
    value: true
  },
  {
    key: "系统消息",
    description: "系统消息将以站内信的形式通知",
    value: true
  },
  {
    key: "待办任务",
    description: "待办任务将以站内信的形式通知",
    value: true
  }
]);

async function onChange(val, item) {
  await editUserProfile({ preferences: list.value });
  message(`${item.key}设置成功`, { type: "success" });
}
onMounted(async () => {
  let userProfile = await getUserProfile() as any;
  let needDelete = false; 
  if (userProfile.data == null||userProfile.data.length === 0) {
    await editUserProfile({ preferences: list.value });
  }
  else { 
    if (list.value.length !== userProfile.data.length) {
      needDelete = true;
    } else { 
      list.value.forEach(item => {
      if (userProfile.data.findIndex(x => x.key === item.key) === -1) {
        needDelete = true;
      }
    });
    }
    if (needDelete) {     
      await deleteUserProfile({ keys: userProfile.data.map(item => item.key) });
      await editUserProfile({ preferences: list.value });     
      userProfile = await getUserProfile() as any;
    }
  }
  list.value = userProfile.data;
});
</script>

<template>
  <div
    :class="[
      'min-w-[180px]',
      deviceDetection() ? 'max-w-[100%]' : 'max-w-[70%]'
    ]"
  >
    <h3 class="my-8!">偏好设置</h3>
    <div v-for="(item, index) in list" :key="index">
      <div class="flex items-center">
        <div class="flex-1">
          <p>{{ item.key }}</p>
          <p class="wp-4">
            <el-text class="mx-1" type="info">
              {{ item.description }}
            </el-text>
          </p>
        </div>
        <el-switch
          v-model="item.value"
          inline-prompt
          active-text="是"
          inactive-text="否"
          @change="val => onChange(val, item)"
        />
      </div>
      <el-divider />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.el-divider--horizontal {
  border-top: 0.1px var(--el-border-color) var(--el-border-style);
}
</style>
